package com.fz.security.provider;

import com.fz.security.config.SecurityConfig;
import com.fz.security.config.SecurityProperties;
import com.fz.security.vo.JwtUser;
import com.fz.service.system.UserService;
import com.fz.utils.RedisUtil;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import java.security.Key;
import java.util.*;
import java.util.stream.Collectors;


@Component
@SuppressWarnings("unchecked")
public class TokenProvider implements InitializingBean {

    private static final String AUTHORITIES_KEY = "auth";
    private final SecurityProperties properties;
    private Key key;

    //权限数据 redis key
    private static final String REDIS_AUTH_KEY = "redis_auth_key";

    @Autowired
    public UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    public TokenProvider(SecurityProperties properties) {
        this.properties = properties;
    }

    private static final Logger logger = LoggerFactory.getLogger(SecurityConfig.class);

    public void afterPropertiesSet() {
        byte[] keyBytes = Decoders.BASE64.decode(properties.getBase64Secret());
        this.key = Keys.hmacShaKeyFor(keyBytes);
    }
    /**
     * @方法描述:  生成token信息 并存入jwt缓存
     * @参数:
     * @返回值:
     * @创建人: I am God
     * @创建时间:: 2021/3/18
     */
    public String createToken(JwtUser jwtUser, Authentication authentication) {
        String authorities = authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.joining(","));

        long now = (new Date()).getTime();
        Date validity = new Date(now + properties.getTokenValidityInSeconds());
        Map<String,Object> map = new HashMap<>();
        map.put("userid",jwtUser.getId());
        map.put("loginid",jwtUser.getLoginId());
        String token = Jwts.builder()
                .setSubject(authentication.getName())
                .claim(AUTHORITIES_KEY, map)
                .signWith(key, SignatureAlgorithm.HS512)
                .setExpiration(validity)
                .compact();
        //将权限信息存入redis当中
        redisUtil.set(REDIS_AUTH_KEY+ jwtUser.getId() + jwtUser.getLoginId(),authorities);
        return token;
    }

    /**
     * @方法描述: 通过token获取用户的授权信息
     * @参数:
     * @返回值:
     * @创建人: I am God
     * @创建时间:: 2021/3/18
     */
   public Authentication getAuthentication(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(token)
                .getBody();

        String result = "";
        if(claims.get(AUTHORITIES_KEY) != null){
            Map<String,Object> map = (Map<String, Object>) claims.get(AUTHORITIES_KEY);
            String userid = map.get("userid").toString();
            String loginid = map.get("loginid").toString();
            result = (String) redisUtil.get(REDIS_AUTH_KEY+ userid + loginid);
        }
        List<GrantedAuthority> authorities = Arrays.stream(result.split(","))
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        User principal = new User(claims.getSubject(), "", authorities);
        return new UsernamePasswordAuthenticationToken(principal, token, authorities);
    }

   public boolean validateToken(String authToken) {
        try {
            Jwts.parser().setSigningKey(key).parseClaimsJws(authToken);
            return true;
        } catch (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) {
            logger.info("Invalid JWT signature.");
            e.printStackTrace();
        } catch (ExpiredJwtException e) {
            logger.info("Expired JWT token.");
            e.printStackTrace();
        } catch (UnsupportedJwtException e) {
            logger.info("Unsupported JWT token.");
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            logger.info("JWT token compact of handler are invalid.");
            e.printStackTrace();
        }
        return false;
    }

}
